import React, {useMemo, useCallback} from 'react';
import {
  View,
  Text,
  TouchableHighlight,
  StyleSheet,
  ScrollView,
} from 'react-native';
import Colors from '../../utils/Colors';
import {useSelector, useDispatch} from 'react-redux';
import {useRoute} from '@react-navigation/native';
import LazyloadImg from '../base/LazyloadImg';

const filterCateFn = (id, arr) => {
  let a = [];
  arr.forEach(item => {
    if (item.id === id) {
      a = arr;
    }
    if (item.son_nodes && item.son_nodes.length > 0) {
      const b = filterCateFn(id, item.son_nodes);
      if (b.length > 0) {
        a = b;
      }
    }
  });
  return a;
};
const Categroys = ({onRequestClose}) => {
  const {params} = useRoute();
  const dispatch = useDispatch();
  const id = params.data.id;
  console.log(params.data.id, 'Cate');
  const navCategories = useSelector(state => state.categroy.navCategories);
  console.log(navCategories);
  const categroysArr = useMemo(() => {
    return filterCateFn(id, navCategories);
  }, [navCategories, id]);
  console.log(categroysArr, 'useMemo');
  const onSelectCategroys = useCallback(
    name => () => {
      onRequestClose();
      dispatch({type: 'categroy/CATEGORY_LIST', payload: name});
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );
  return (
    <View style={styles.sizeBox}>
      <ScrollView horizontal={true} showsHorizontalScrollIndicator={false}>
        {categroysArr.map(item => {
          return (
            <TouchableHighlight
              activeOpacity={1}
              underlayColor={Colors.white}
              onPress={onSelectCategroys(item.name)}
              key={item.id}>
              <View style={styles.items}>
                <LazyloadImg style={styles.img} source={{uri: item.icon}} />
                <Text style={styles.cateText}>{item.name}</Text>
              </View>
            </TouchableHighlight>
          );
        })}
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  sizeBox: {
    backgroundColor: Colors.white,
    width: '100%',
  },
  items: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'flex-start',
    flexDirection: 'column',
    height: 70,
    width: 70,
    margin: 10,
  },
  img: {
    width: 50,
    height: 50,
  },
  cateText: {
    fontSize: 10,
    color: Colors.patFontGray2,
    textAlign: 'center',
  },
});
export default Categroys;
